package com.gdpu.project.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.gdpu.page.vo.QueryResult;
import com.gdpu.project.dao.CgPatentDao;
import com.gdpu.project.vo.CgInnovate;
import com.gdpu.project.vo.CgPatent;
import com.gdpu.project.vo.CgProject;
import com.gdpu.project.vo.CgTreatise;


public class CgPatentDaoImpl extends HibernateDaoSupport implements CgPatentDao {
	private static final Log log = LogFactory.getLog(CgPatentDaoImpl.class);
	// property constants
	public static final String PATENT_ID = "patentId";
	public static final String TEACHER_ID = "teacherId";
	public static final String PATENT_TITLE = "patentTitle";
	public static final String SHOU_YI_HAO = "shouYiHao";
	public static final String PATENT_TYPE = "patentType";
	public static final String XUE_KE = "xueKe";
	public static final String SCHOOL_SIGN = "schoolSign";
	public static final String PUBLISH_RANGE = "publishRange";
	public static final String KE_YAN_FEN = "keYanFen";
	public static final String COMMENT = "comment";

	protected void initDao() {
		// do nothing
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#save(com.gdpu.project.vo.CgPatent)
	 */
	public void save(CgPatent transientInstance) {
		log.debug("saving CgPatent instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#delete(com.gdpu.project.vo.CgPatent)
	 */
	public void delete(CgPatent persistentInstance) {
		log.debug("deleting CgPatent instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#findById(java.lang.Integer)
	 */
	public CgPatent findById(java.lang.Integer id) {
		log.debug("getting CgPatent instance with id: " + id);
		try {
			CgPatent instance = (CgPatent) getHibernateTemplate().get(
					"com.gdpu.project.vo.CgPatent", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#findByExample(com.gdpu.project.vo.CgPatent)
	 */
	@SuppressWarnings("unchecked")
	public QueryResult<CgPatent> findByExample(CgPatent instance,int firstindex,int maxresult) {
		log.debug("finding CgPatent instance by example");
		try {
			QueryResult<CgPatent> queryResult=new QueryResult<CgPatent>();
			List<CgPatent> results = getHibernateTemplate().findByExample(instance).subList(firstindex, firstindex+maxresult-1);
			log.debug("find by example successful, result size: "
					+ results.size());
			queryResult.setResultlist(results);
			int count= getHibernateTemplate().findByExample(instance).size();
			queryResult.setTotalrecord(count);
			return queryResult;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#findByProperty(java.lang.String, java.lang.Object)
	 */
	public QueryResult<CgPatent> findByProperty(String propertyName, Object value,int firstindex,int maxresult) {
		log.debug("finding CgPatent instance with property: " + propertyName
				+ ", value: " + value);
		try {
			Query query1=getSessionFactory().getCurrentSession().createQuery("from CgPatent as model where model."
					+ propertyName + " like :propertyName");
			Query query2=getSessionFactory().getCurrentSession().createQuery("select count(*) from CgPatent as model where model."
					+ propertyName + " like :propertyName");
			if(value!=null){
				query1.setParameter("propertyName", value);
				query2.setParameter("propertyName", value);
			}else{
				query1.setParameter("propertyName", "%%");
				query2.setParameter("propertyName", "%%");
			}
			if(firstindex!=-1&&maxresult!=-1){
				query1.setFirstResult(firstindex).setMaxResults(maxresult);
			}
			QueryResult<CgPatent> queryResult=new QueryResult<CgPatent>();
			queryResult.setResultlist(query1.list());
			queryResult.setTotalrecord((Long)query2.uniqueResult());
			return queryResult;
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<CgPatent> nfindByProperty(String propertyName, String value,Date begin,Date end) {
		log.debug("finding CgPatent instance with property: " + propertyName
				+ ", value: " + value);
		try {
			StringBuilder builder=new StringBuilder();
			String queryString = "from CgPatent as model where model."
				+ propertyName + "= ?";
			builder.append(queryString);
			if(begin!=null){
				builder.append(" and model.obtainCertificateTime>=? ");
			}
			if(end!=null){
				builder.append(" and model.obtainCertificateTime<=? ");
			}
			List<Object> pramList=new ArrayList<Object>();
			if(value!=null){
				pramList.add(value);
			}
			if(begin!=null){
				pramList.add(begin);
			}
			if(end!=null){
				pramList.add(end);
			}
			
			return (List<CgPatent>)getHibernateTemplate().find(builder.toString(), pramList.toArray());
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	
	/**
	 * 分页查询专著
	 */
	public QueryResult<CgPatent> nfindByProperty(String propertyName,List<String> value,Date begin,Date end,int firstindex,int maxresult) {
		log.debug("finding CgPatent instance with property: "
				+ propertyName + ", value: " + value);
		try {
			QueryResult<CgPatent> queryResult=new QueryResult<CgPatent>();
			//String val[]=(String[])value.toArray();
			StringBuffer queryStr=new StringBuffer();
			queryStr.append("from CgPatent as model where model."+ propertyName + " in (:value)");
			if(begin!=null){
				queryStr.append(" and model.obtainCertificateTime>=:begin");
			}
			if(end!=null){
				queryStr.append(" and model.obtainCertificateTime<:end");
			}
			Query query=getSessionFactory().getCurrentSession().createQuery(queryStr.toString());
			query.setParameterList("value", value);//绑定参数
			if(begin!=null){
				query.setParameter("begin", begin);
			}
			if(end!=null){
				query.setParameter("end", end);
			}
			if(firstindex!=-1&&maxresult!=-1){
				query.setFirstResult(firstindex).setMaxResults(maxresult);
			}
			if(value.size()>0){
				queryResult.setResultlist(query.list());
			}
			queryStr.delete(0,queryStr.length());//清除之前的字符窜
			queryStr.append("select count(*) from CgPatent as model where model."+ propertyName + " in (:value)");
			if(begin!=null){
				queryStr.append(" and model.obtainCertificateTime>=:begin");
			}
			if(end!=null){
				queryStr.append(" and model.obtainCertificateTime<:end");
			}
			query=getSessionFactory().getCurrentSession().createQuery(queryStr.toString());
			query.setParameterList("value", value);//绑定参数
			if(query.getQueryString().indexOf(" and model.obtainCertificateTime>=:begin")!=-1){
				query.setParameter("begin", begin);
			}
			if(query.getQueryString().indexOf(" and model.obtainCertificateTime<:end")!=-1){
				query.setParameter("end", end);
			}
			
			if(value.size()>0){
				queryResult.setTotalrecord((Long)query.uniqueResult());
			}
			
			return queryResult;
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	 
	
	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#findByPatentId(java.lang.Object)
	 */
	public QueryResult<CgPatent> findByPatentId(Object patentId,int firstindex,int maxresult) {
		return findByProperty(PATENT_ID, patentId, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#findByTeacherId(java.lang.Object)
	 */
	public QueryResult<CgPatent> findByTeacherId(Object teacherId,int firstindex,int maxresult) {
		return findByProperty(TEACHER_ID, teacherId, firstindex, maxresult);
	}
	public QueryResult<CgPatent> findByTeacherId(Object teacherId) {
		return findByProperty(TEACHER_ID, teacherId,-1,-1);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#findByPatentTitle(java.lang.Object)
	 */
	public QueryResult<CgPatent> findByPatentTitle(Object patentTitle,int firstindex,int maxresult) {
		return findByProperty(PATENT_TITLE, patentTitle, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#findByShouYiHao(java.lang.Object)
	 */
	public QueryResult<CgPatent> findByShouYiHao(Object shouYiHao,int firstindex,int maxresult) {
		return findByProperty(SHOU_YI_HAO, shouYiHao, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#findByPatentType(java.lang.Object)
	 */
	public QueryResult<CgPatent> findByPatentType(Object patentType,int firstindex,int maxresult) {
		return findByProperty(PATENT_TYPE, patentType, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#findByXueKe(java.lang.Object)
	 */
	public QueryResult<CgPatent> findByXueKe(Object xueKe,int firstindex,int maxresult) {
		return findByProperty(XUE_KE, xueKe, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#findBySchoolSign(java.lang.Object)
	 */
	public QueryResult<CgPatent> findBySchoolSign(Object schoolSign,int firstindex,int maxresult) {
		return findByProperty(SCHOOL_SIGN, schoolSign, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#findByPublishRange(java.lang.Object)
	 */
	public QueryResult<CgPatent> findByPublishRange(Object publishRange,int firstindex,int maxresult) {
		return findByProperty(PUBLISH_RANGE, publishRange, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#findByKeYanFen(java.lang.Object)
	 */
	public QueryResult<CgPatent> findByKeYanFen(Object keYanFen,int firstindex,int maxresult) {
		return findByProperty(KE_YAN_FEN, keYanFen, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#findByComment(java.lang.Object)
	 */
	public QueryResult<CgPatent> findByComment(Object comment,int firstindex,int maxresult) {
		return findByProperty(COMMENT, comment, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#findAll()
	 */
	@SuppressWarnings("unchecked")
	public QueryResult<CgPatent> findAll(int firstindex,int maxresult) {
		log.debug("finding all CgPatent instances");
		try {
			Query query=getSessionFactory().getCurrentSession().createQuery("from CgPatent cgPatent");
			if(firstindex!=-1&&maxresult!=-1){
				query.setFirstResult(firstindex).setMaxResults(maxresult);
			}
			QueryResult<CgPatent> queryResult=new QueryResult<CgPatent>();
			queryResult.setResultlist(query.list());
			query=getSessionFactory().getCurrentSession().createQuery("select count(*) from CgPatent cgPatent");
			queryResult.setTotalrecord((Long)query.uniqueResult());
			return queryResult;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#merge(com.gdpu.project.vo.CgPatent)
	 */
	public CgPatent merge(CgPatent detachedInstance) {
		log.debug("merging CgPatent instance");
		try {
			CgPatent result = (CgPatent) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#attachDirty(com.gdpu.project.vo.CgPatent)
	 */
	public void attachDirty(CgPatent instance) {
		log.debug("attaching dirty CgPatent instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgPatentDao#attachClean(com.gdpu.project.vo.CgPatent)
	 */
	public void attachClean(CgPatent instance) {
		log.debug("attaching clean CgPatent instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static CgPatentDao getFromApplicationContext(ApplicationContext ctx) {
		return (CgPatentDao) ctx.getBean("CgPatentDAO");
	}

	public int count(String teacherId) {
		String hql="from CgPatent as c where c.teacherId=?";
		int count=0;
		List<CgPatent> list=(List<CgPatent>)getHibernateTemplate().find(hql, teacherId);
		Iterator<CgPatent> it=list.iterator();
		while(it.hasNext())
		{
			CgPatent c=it.next();
			if(c.getKeYanFen()==0f){
				count=count+0;
			}
			else{
				count=count+(int)c.getKeYanFen();
			}
		}
		return count;
	}
}